package com.rayc.mall.gateway.filter;

import cn.hutool.core.text.AntPathMatcher;
import com.rayc.mall.common.exception.UnauthorizedException;
import com.rayc.mall.common.utils.CollUtils;
import com.rayc.mall.common.utils.JwtTool;
import com.rayc.mall.gateway.properties.FilterProperties;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import javax.annotation.Resource;
import java.util.List;

/**
 * @Author: Ray-C
 * @CreateTime: 2025-03-24
 * @Description: 登录过滤器
 * @Version: 1.0
 */
@Component
public class LoginFilter implements GlobalFilter, Ordered {
    @Resource
    private JwtTool jwtTool;

    @Resource
    private FilterProperties filterProperties;

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 获取Request
        ServerHttpRequest request = exchange.getRequest();
        // 判断是否不需要拦截
        if (isExclude(request.getPath().toString())) {
            // 无需拦截，直接放行
            return chain.filter(exchange);
        }
        // 获取请求头中的token
        String token = null;
        List<String> headers = request.getHeaders().get("authorization");
        if (!CollUtils.isEmpty(headers)) {
            token = headers.get(0);
        }
        if (token != null && token.startsWith("Bearer ")) {
            token = token.substring(7);
        }
        // 校验并解析token
        Long userId = null;
        try {
            userId = jwtTool.parseToken(token);
        } catch (UnauthorizedException e) {
            // 如果无效，拦截
            ServerHttpResponse response = exchange.getResponse();
//            response.setRawStatusCode(401);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        // 如果有效，传递用户信息
        // 更新过滤器
        String userIdStr = userId.toString();
        ServerWebExchange swe = exchange.mutate().request(builder -> builder.header("user-id", userIdStr)).build();
        // 放行
        return chain.filter(swe);
    }

    private boolean isExclude(String path) {
        List<String> excludedPaths = filterProperties.getExcludedPaths();
        AntPathMatcher antPathMatcher = new AntPathMatcher();
        for (String excludedPath : excludedPaths) {
            if (antPathMatcher.match(excludedPath, path)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public int getOrder() {
        return 0;
    }
}
